package com.zmj.dubboannotation.productservice.productservice.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zmj.commoncore.dto.ProductDTO;
import com.zmj.commoncore.utils.Descartes;
import com.zmj.commoncore.utils.SKUGenerator;
import com.zmj.dubboannotation.productservice.mapper.MallProductMapper;
import com.zmj.dubboannotation.productservice.mapper.SkuProductMapper;
import com.zmj.dubboannotation.productservice.repository.ProductAttrValueRepository;
import com.zmj.dubboannotation.productservice.repository.ProductAttributeRepository;
import com.zmj.dubboannotation.serviceapi.api.ProductService;
import com.zmj.dubboannotation.serviceapi.model.*;
import com.zmj.dubboannotation.serviceapi.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by: meijun
 * Date: 2018/09/15 12:20
 */
@Service(interfaceClass = ProductService.class)
@Component
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private MallProductMapper productMapper;

    @Autowired
    private ProductAttributeRepository productAttributeRepository;

    @Autowired
    private ProductAttrValueRepository productAttrValueRepository;

    @Autowired
    private SkuProductMapper skuProductMapper;


    @Override
    public List<MallProduct> findAll() {
        return productMapper.selectAll();
    }


    @Override
    public ProductVO findProductBySkuId(String skuId) {
        return productMapper.findProductBySkuId(skuId);
    }


    @Override
    public PageInfo<ProductVO> findProductByParam(Integer pageNum, Integer pageSize,MallProduct product) {

        PageHelper.startPage(pageNum,pageSize);
        List<ProductVO> list = productMapper.findProductByParam(product);
        PageInfo<ProductVO> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo<ProductVO> findProductByList(Integer pageNum, Integer pageSize, List<MemberProductCollection> list) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductVO> productVOList = productMapper.findProductByList(list);
        PageInfo<ProductVO> pageInfo = new PageInfo(productVOList);
        return pageInfo;
    }

    @Override
    public List<ProductVO> findAllESProduct() {
        return productMapper.findAllESProduct();
    }

    @Override
    public PageInfo<ProductVO> findRecommend(Integer pageNum, Integer pageSize, List<MemberActionLog> actionLogs) {
        return null;
    }

    @Override
    @Transactional
    public int save(ProductDTO productDTO) {
        MallProduct product = new MallProduct();
        product.setId(IdWorker.getIdStr());
        BeanUtils.copyProperties(productDTO,product);
        /**
         * 解析 attributeValues
         * attributeValues : “属性id1:属性值id1/属性值id2,属性id12:属性值id1/属性值id2,”
         * 例  attributeValues = "11(尺码id):3/4,12(颜色ID):1/2"
         */
        String[] attributeValues = productDTO.getAttributes().split(",");
        Map<String, String> attributeMap = autoMap(attributeValues);

        List<ProductAttribute> productAttributes = productAttributeRepository.findByCategoryId(product.getCategoryId());
        //取出attributeId查询
        List<Integer> mapKey = getMapKey(attributeMap);
        //传入的attributeId 对应的 value 值
        List<ProductAttrValue> productAttrValues = productAttrValueRepository.findByAttributeIdIsIn(mapKey);

        List<List<String>> list = new ArrayList<>();
        JSONArray baseArray = new JSONArray();
        try {
            for(Map.Entry<String, String> entry: attributeMap.entrySet()){
                JSONObject baseObject = new JSONObject();
                String[] split = entry.getValue().split("/");
                JSONArray attrbutes = new JSONArray();
                for (String  id:split) {
                    JSONObject object = new JSONObject();
                    object.put("attributeValueId",id);
                    for (ProductAttrValue productAttrbute:productAttrValues) {
                        if(productAttrbute.getId().intValue() == Integer.parseInt(id)) {
                            object.put("attributeValueName",productAttrbute.getAttrVale());
                        }
                    }
                    attrbutes.add(object);
                }
                baseObject.put("id",entry.getKey());
                for (ProductAttribute productProperty:productAttributes) {
                    if(productProperty.getId() == Integer.parseInt(entry.getKey())) {
                        baseObject.put("attributeName",productProperty.getAttrName());
                    }
                }
                baseObject.put("attrbutes",attrbutes);
                baseArray.add(baseObject);

                list.add(Arrays.asList(split));
            }

            List<List<String>> recursiveResult = new ArrayList<List<String>>();
            // 递归实现笛卡尔积
            Descartes.recursive(list, recursiveResult, 0, new ArrayList<String>());

            for (List<String> lists : recursiveResult) {
                JSONArray array = new JSONArray();
                String attributeIds = "";
                String attributeNames = "";

                for (String string : lists) {
                    JSONObject object = new JSONObject();
                    object.put("attributeValueId",string);
                    attributeIds +=  string + "/";
                    for (ProductAttrValue productAttrValue:productAttrValues) {
                        if(productAttrValue.getId().intValue()  == Integer.parseInt(string)) {
                            object.put("attributeValueName",productAttrValue.getAttrVale());
                            attributeNames += productAttrValue.getAttrVale() + "-";
                        }
                    }
                    for (ProductAttrValue productAttrValue:productAttrValues) {
                        if(productAttrValue.getId().intValue() == Integer.parseInt(string)) {
                            for (ProductAttribute productAttribute:productAttributes) {
                                if(productAttribute.getId().intValue() == productAttrValue.getAttributeId().intValue()) {
                                    object.put("attributeName",productAttribute.getAttrName());
                                }
                            }
                        }
                    }
                    array.add(object);
                }

                SkuProduct skuProduct = new SkuProduct();

                //设置主键id
                skuProduct.setId(IdWorker.getIdStr());
                skuProduct.setProductId(product.getId());
                skuProduct.setProductStock(product.getProductStock());

                //生成sku
                skuProduct.setSkuProductId(SKUGenerator.createSKU(skuProduct.getId(),attributeIds));
                log.info("skuProductId: {} ,length: {}" , skuProduct.getSkuProductId() ,String.valueOf(skuProduct.getSkuProductId()));
                //生成skuCode
                ///TODO
                //产品标题追加属性
                skuProduct.setSkuName(SKUGenerator.nameSpilt(product.getProductName() + "  " + attributeNames));

                //设置属性
                skuProduct.setAttrValue(array.toString());

                //生成sku
                skuProductMapper.insert(skuProduct);
            }
            //生成商品基本信息
            productMapper.insert(product);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("[创建产品] 创建产品出现异常.");
            return -1;
        }
        return 0;
    }

    /**
     * 将传入的attributes转为 map
     * @param ids
     * @return
     */
    private Map<String,String> autoMap(String[] ids){
        HashMap<String,String> map = new HashMap<>();
        for (String p: ids) {
            String[] split = p.split(":");
            map.put(split[0],split[1]);
        }
        return map;
    }

    /**
     * 从map中取出key ,也就是attributeId
     * @param map
     * @return
     */
    private List<Integer> getMapKey(Map<String, String> map){
        Set<String> set = map.keySet();
        Iterator<String> iterator = set.iterator();
        List<Integer> list = Lists.newArrayList();
        while (iterator.hasNext()) {
            String key = iterator.next();
            list.add(Integer.parseInt(key));
        }
        return list;
    }
}
